package com.aimosheng.main.views;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.aimosheng.common.bean.ChatReceiveGiftBean;
import com.aimosheng.common.event.FollowEvent;
import com.aimosheng.common.http.HttpCallback;
import com.aimosheng.common.presenter.GiftAnimViewHolder;
import com.aimosheng.im.bean.ImMessageBean;
import com.aimosheng.main.R;
import com.aimosheng.video.adapter.VideoScrollAdapter;
import com.aimosheng.video.bean.VideoBean;
import com.aimosheng.video.custom.VideoLoadingBar;
import com.aimosheng.video.event.VideoCommentEvent;
import com.aimosheng.video.event.VideoLikeEvent;
import com.aimosheng.video.event.VideoShareEvent;
import com.aimosheng.video.event.VideoWatchEvent;
import com.aimosheng.video.http.VideoHttpConsts;
import com.aimosheng.video.http.VideoHttpUtil;
import com.aimosheng.video.views.VideoPlayViewHolder;
import com.aimosheng.video.views.VideoPlayWrapViewHolder;
import com.alibaba.fastjson.JSON;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainVideoViewHolder extends AbsMainViewHolder implements VideoPlayViewHolder.ActionListener, VideoScrollAdapter.ActionListener, OnRefreshLoadMoreListener {


    private VideoPlayViewHolder mVideoPlayViewHolder;
    private View mPlayView;
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private VideoScrollAdapter mVideoScrollAdapter;
    private VideoPlayWrapViewHolder mVideoPlayWrapViewHolder;
    private VideoLoadingBar mVideoLoadingBar;
    private GiftAnimViewHolder mGiftAnimViewHolder;
    private RelativeLayout mRoot;
    private VideoBean mVideoBean;
    private List<VideoBean> mVideoBeans;
    private boolean mPaused;//生命周期暂停
    private int mPage = 1;


    public MainVideoViewHolder(Context context, ViewGroup parentView) {
        super(context, parentView);
    }

    public MainVideoViewHolder(Context context, ViewGroup parentView, Object... args) {
        super(context, parentView, args);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_main_video;
    }

    @Override
    public void init() {
        mRoot = findViewById(R.id.root);
        mVideoBeans = new ArrayList<>();
        mVideoPlayViewHolder = new VideoPlayViewHolder(mContext, null);
        mVideoPlayViewHolder.setOnDoubleClickListener(new VideoPlayViewHolder.OnDoubleClickListener() {
            @Override
            public void onDoubleClick(View view) {
                if(mVideoPlayWrapViewHolder != null){
                    mVideoPlayWrapViewHolder.clickLike();
                }
            }
        });
        mVideoPlayViewHolder.setActionListener(this);
        mPlayView = mVideoPlayViewHolder.getContentView();
        mRefreshLayout = (SmartRefreshLayout) findViewById(com.aimosheng.video.R.id.refreshLayout);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRecyclerView = (RecyclerView) findViewById(com.aimosheng.video.R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mVideoScrollAdapter = new VideoScrollAdapter(mContext, mVideoBeans, 0);
        mVideoScrollAdapter.setActionListener(this);
        mRecyclerView.setAdapter(mVideoScrollAdapter);
        mVideoLoadingBar = (VideoLoadingBar) findViewById(com.aimosheng.video.R.id.video_loading);
        onRefresh(mRefreshLayout);
        EventBus.getDefault().register(this);
    }


    @Override
    public void onPlayBegin() {
        if (mVideoLoadingBar != null) {
            mVideoLoadingBar.setLoading(false);
        }
    }

    @Override
    public void onPlayLoading() {
        if (mVideoLoadingBar != null) {
            mVideoLoadingBar.setLoading(true);
        }
    }

    @Override
    public void onFirstFrame() {
        if (mVideoPlayWrapViewHolder != null) {
            mVideoPlayWrapViewHolder.onFirstFrame();
        }
    }


    @Override
    public void onPageSelected(VideoPlayWrapViewHolder videoPlayWrapViewHolder, boolean needLoadMore) {
        if (videoPlayWrapViewHolder != null) {
            VideoBean videoBean = videoPlayWrapViewHolder.getVideoBean();
            if (videoBean != null) {
                mVideoBean = videoBean;
                mVideoPlayWrapViewHolder = videoPlayWrapViewHolder;
                videoPlayWrapViewHolder.addVideoView(mPlayView);
                if (mVideoPlayViewHolder != null) {
                    mVideoPlayViewHolder.startPlay(videoBean);
                }
                if (mVideoLoadingBar != null) {
                    mVideoLoadingBar.setLoading(true);
                }
            }
            if (needLoadMore) {
                onLoadMore(mRefreshLayout);
            }
        }
    }

    @Override
    public void onPageOutWindow(VideoPlayWrapViewHolder vh) {
        if (mVideoPlayWrapViewHolder != null && mVideoPlayWrapViewHolder == vh && mVideoPlayViewHolder != null) {
            mVideoPlayViewHolder.stopPlay();
        }
    }

    @Override
    public void onVideoDeleteAll() {
    }


    @Override
    public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
        mPage++;
        VideoHttpUtil.getMainRecommendVideo(mPage,  new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                List<VideoBean> videoBeans = JSON.parseArray(Arrays.toString(info), VideoBean.class);
                mRefreshLayout.finishLoadMore();
                mVideoScrollAdapter.insertList(videoBeans);
            }
        });
    }

    @Override
    public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
        mPage = 1;
        VideoHttpUtil.getMainRecommendVideo(mPage, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                List<VideoBean> videoBeans = JSON.parseArray(Arrays.toString(info), VideoBean.class);
                if(videoBeans != null && !videoBeans.isEmpty()){
                    for (int i = 0; i < videoBeans.size(); i++) {
                        VideoBean videoBean = videoBeans.get(i);
                        videoBean.transform();
                    }
                }
                mRefreshLayout.finishRefresh();
                mVideoScrollAdapter.setList(videoBeans);
            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();
        if (!mPaused && mVideoPlayViewHolder != null) {
            mVideoPlayViewHolder.pausePlay();
            mPaused = true;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mPaused && mVideoPlayViewHolder != null && isShowed()) {
            mVideoPlayViewHolder.resumePlay();
            mPaused = false;
        }
    }

    @Override
    public void setShowed(boolean showed) {
        super.setShowed(showed);
        if(showed){
            if (mPaused && mVideoPlayViewHolder != null) {
                mVideoPlayViewHolder.resumePlay();
                mPaused = false;
            }
        }else{
            if (!mPaused && mVideoPlayViewHolder != null) {
                mVideoPlayViewHolder.pausePlay();
                mPaused = true;
            }
        }
    }

    /**
     * 关注发生变化
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFollowEvent(FollowEvent e) {
        if (mVideoScrollAdapter != null && mVideoPlayWrapViewHolder != null) {
            VideoBean videoBean = mVideoPlayWrapViewHolder.getVideoBean();
            if (videoBean != null) {
                mVideoScrollAdapter.onFollowChanged(!mPaused, videoBean.getId(), e.getToUid(), e.getIsAttention());
            }
        }
    }

    /**
     * 点赞发生变化
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoLikeEvent(VideoLikeEvent e) {
        if (mVideoScrollAdapter != null) {
            mVideoScrollAdapter.onLikeChanged(!mPaused, e.getVideoId(), e.getIsLike(), e.getLikeNum());
        }
    }

    /**
     * 观看数发生变化
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoWatchEvent(VideoWatchEvent e) {
        if (mVideoScrollAdapter != null) {
            mVideoScrollAdapter.onWatchNumChanged(e.getVideoId(), e.getWatchNum());
        }
    }

    /**
     * 分享数发生变化
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoShareEvent(VideoShareEvent e) {
        if (mVideoScrollAdapter != null) {
            mVideoScrollAdapter.onShareChanged(e.getVideoId(), e.getShareNum());
        }
    }

    /**
     * 评论数发生变化
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoCommentEvent(VideoCommentEvent e) {
        if (mVideoScrollAdapter != null) {
            mVideoScrollAdapter.onCommentChanged(e.getVideoId(), e.getCommentNum());
        }
    }

    /**
     * 收到发送礼物消息的回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImMessageBean(ImMessageBean bean) {
        if (mPaused || mVideoBean == null) {
            return;
        }
        String toUid = mVideoBean.getUid();
        if (!TextUtils.isEmpty(toUid) && toUid.equals(bean.getUid())) {
            ChatReceiveGiftBean giftBean = bean.getGiftBean();
            if (giftBean != null) {
                showGift(bean.getGiftBean());
            }
        }
    }

    /**
     * 显示礼物动画
     */
    public void showGift(ChatReceiveGiftBean bean) {
        if (mGiftAnimViewHolder == null) {
            mGiftAnimViewHolder = new GiftAnimViewHolder(mContext, mRoot);
            mGiftAnimViewHolder.addToParent();
        }
        mGiftAnimViewHolder.showGiftAnim(bean);
    }

    @Override
    public void release() {
        super.release();
        VideoHttpUtil.cancel(VideoHttpConsts.GET_MAIN_RECOMMEND_VIDEO);
        VideoHttpUtil.cancel(VideoHttpConsts.SET_VIDEO_SHARE);
        VideoHttpUtil.cancel(VideoHttpConsts.VIDEO_DELETE);
        VideoHttpUtil.cancel(VideoHttpConsts.VIDEO_PUBLIC);
        EventBus.getDefault().unregister(this);
        if (mVideoPlayViewHolder != null) {
            mVideoPlayViewHolder.release();
        }
        mVideoPlayWrapViewHolder = null;
        if (mVideoLoadingBar != null) {
            mVideoLoadingBar.endLoading();
        }
        mVideoLoadingBar = null;
        if (mRefreshLayout != null) {
            mRefreshLayout.setOnRefreshListener(null);
        }
        mRefreshLayout = null;
        if (mVideoScrollAdapter != null) {
            mVideoScrollAdapter.release();
        }
        mVideoScrollAdapter = null;
    }

}
